package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.constants.ArticleConstants;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.thread.AppThreadLocalUtil;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.freemarker.FreemarkerGenerator;
import com.heima.common.redis.CacheService;
import com.heima.minio.MinIoTemplate;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.article.mess.ArticleVisitStreamMess;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.pojos.SearchArticleVo;
import com.heima.model.user.pojos.ApUser;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private FreemarkerGenerator freemarkerGenerator;

    @Autowired
    private MinIoTemplate minIoTemplate;

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    @Autowired
    private CacheService cacheService;


    @Override
    public List<ApArticle> load(ArticleHomeDto dto, Short loadtypeLoadMore) {
        return apArticleMapper.articleLoad(dto, loadtypeLoadMore);
    }

    @Override
    public void updateScore(ArticleVisitStreamMess mess) {
        // 更新数据库
        ApArticle article = updateArticle(mess);
        if (article == null) {
            return;
        }

        // 计算文章分值
        Integer score = compute(article);

        // 替换当前文章对应频道的热点数据
        replaceToRedis(article, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + article.getChannelId());

        // 替换推荐频道热点数据
        replaceToRedis(article, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);
    }

    /**
     * 替换缓存数据
     *
     * @param article 文章内容
     * @param score   分值
     * @param key     缓存键
     */
    private void replaceToRedis(ApArticle article, Integer score, String key) {
        // 根据key获取缓存数据
        String cache = cacheService.get(key);
        if (StringUtils.isEmpty(cache)) {
            return;
        }

        List<HotArticleVo> hotArticleVos = JSON.parseArray(cache, HotArticleVo.class);
        if (CollectionUtils.isEmpty(hotArticleVos)) {
            return;
        }

        boolean flag = false;

        // 如果当前内容存在于缓存，则替换缓存分值
        for (HotArticleVo hotArticleVo : hotArticleVos) {
            if (hotArticleVo == null) {
                continue;
            }

            if (hotArticleVo.getId().equals(article.getId())) {
                hotArticleVo.setScore(score);
                flag = true;
                break;
            }
        }

        //如果缓存中不存在，查询缓存中分值最小的一条数据，进行分值的比较，如果当前文章的分值大于缓存中的数据，就替换
        if (flag) {
            if (hotArticleVos.size() >= 30) {
                // 排序
                hotArticleVos = hotArticleVos.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
                // 取最后一条
                HotArticleVo lastHot = hotArticleVos.get(hotArticleVos.size() - 1);
                // 如果最后一条分值比当前文章分值小，则替换
                if (lastHot.getScore() < score) {
                    hotArticleVos.remove(lastHot);
                    HotArticleVo hot = new HotArticleVo();
                    BeanUtils.copyProperties(article, hot);
                    hot.setScore(score);
                    hotArticleVos.add(hot);
                }
            } else {
                HotArticleVo hot = new HotArticleVo();
                BeanUtils.copyProperties(article, hot);
                hot.setScore(score);
                hotArticleVos.add(hot);
            }
        }

        // 重新排序
        hotArticleVos = hotArticleVos.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());

        // 缓存到redis
        cacheService.set(key, JSON.toJSONString(hotArticleVos));
    }

    /**
     * 更新文章MySQL数据
     *
     * @param mess messmess
     * @return ApArticle
     */
    private ApArticle updateArticle(ArticleVisitStreamMess mess) {
        ApArticle apArticle = apArticleMapper.selectById(mess.getArticleId());
        if (apArticle == null) {
            log.warn("文章id" + mess.getArticleId() + "不存在");
            return null;
        }

        Integer views = apArticle.getViews();
        Integer likes = apArticle.getLikes();
        Integer comment = apArticle.getComment();
        Integer collection = apArticle.getCollection();

        apArticle.setComment(comment == null ? mess.getComment() : comment + mess.getComment());
        apArticle.setLikes(likes == null ? mess.getLike() : likes + mess.getLike());
        apArticle.setCollection(collection == null ? mess.getCollect() : collection + mess.getCollect());
        apArticle.setViews(views == null ? mess.getView() : views + mess.getView());

        apArticleMapper.updateById(apArticle);

        return apArticle;
    }

    /**
     * 计算文章评分
     *
     * @param apArticle apArticle
     * @return Integer
     */
    private Integer compute(ApArticle apArticle) {
        Integer views = apArticle.getViews();
        Integer likes = apArticle.getLikes();
        Integer comment = apArticle.getComment();
        Integer collection = apArticle.getCollection();

        Integer score = 0;
        if (views != null) {
            score += views;
        }

        if (likes != null) {
            score += likes * 3;
        }

        if (comment != null) {
            score += comment * 5;
        }

        if (collection != null) {
            score += collection * 8;
        }

        return score;
    }

    /**
     * 加载文章列表
     * @param dto
     * @param firstPage true  是首页  flase 非首页
     * @return
     */
    @Override
    public ResponseResult load2(ArticleHomeDto dto, boolean firstPage) {
        if(firstPage){
            String jsonStr = cacheService.get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
            if(StringUtils.isNotBlank(jsonStr)){
                List<HotArticleVo> hotArticleVoList = JSON.parseArray(jsonStr, HotArticleVo.class);
                ResponseResult responseResult = ResponseResult.okResult(hotArticleVoList);
                return responseResult;
            }
        }
        List<ApArticle> list = load(dto, ArticleConstants.LOADTYPE_LOAD_MORE);
        return ResponseResult.okResult(list);
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public ResponseResult saveArticle(ArticleDto dto) {
        // 1. dto判空
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto, apArticle);
        //判断dto中是否有id,没有
        if (dto.getId() == null) {
            //新增逻辑
            //新增article表
            int successNum = apArticleMapper.insert(apArticle);
            if (successNum < 1) {
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
            }
            //新增article_config表
            ApArticleConfig apArticleConfig = new ApArticleConfig();
            //设置article_id
            apArticleConfig.setArticleId(apArticle.getId());
            //设置is_comment
            apArticleConfig.setIsComment(true);
            //设置is_forward
            apArticleConfig.setIsForward(true);
            //设置is_down
            apArticleConfig.setIsDown(false);
            //设置is_delete
            apArticleConfig.setIsDelete(false);

            //向config表插入
            int successNum2 = apArticleConfigMapper.insert(apArticleConfig);
            if (successNum2 < 1) {
                throw new RuntimeException("配置表插入失败");
            }

            //新增content表
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(dto.getContent());

            //向content插入
            int successNum3 = apArticleContentMapper.insert(apArticleContent);
            if (successNum3 < 1) {
                throw new RuntimeException("关联表插入失败");
            }
            CreateHtmlAndUploadMINIO(apArticle.getId());
            return ResponseResult.okResult(apArticle.getId());
        } else {
            //有id
            //修改逻辑
            int successNum = apArticleMapper.updateById(apArticle);
            if (successNum < 1) {
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
            }
            // 4.2 修改article_content表
            LambdaQueryWrapper<ApArticleContent> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ApArticleContent::getArticleId, apArticle.getId());
            // 修改的数据
            ApArticleContent articleContent = new ApArticleContent();
            articleContent.setContent(dto.getContent());

            int contentUpdateResult = apArticleContentMapper.update(articleContent, wrapper);
            if (contentUpdateResult < 1) {
                throw new RuntimeException("内容表修改失败");
            }
            CreateHtmlAndUploadMINIO(dto.getId());
            return ResponseResult.okResult(dto.getId());
        }
    }

    /**
     * 详情页用户行为回显
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        Integer userId = user.getId();
        if (userId == null || userId == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        boolean islike = false, isunlike = false, iscollection = false, isfollow = false;
        //判断是否点赞
        String likeResult = (String) cacheService.hGet(BehaviorConstants.LIKE_BEHAVIOR + dto.getArticleId(), userId.toString());
        //如果存在,就将like设为true
        if (StringUtils.isNotEmpty(likeResult)) {
            islike = true;
        }
        //判断是否为不喜欢
        String unlikeResult = (String) cacheService.hGet(BehaviorConstants.UN_LIKE_BEHAVIOR + dto.getArticleId(), userId.toString());
        //如果存在,就将unlike设为true
        if (StringUtils.isNotEmpty(unlikeResult)) {
            isunlike = true;
        }
        //判断是否为收藏
        String collectionResult = (String) cacheService.hGet(BehaviorConstants.COLLECTION_BEHAVIOR + dto.getArticleId(), userId.toString());
        //如果存在,就将收藏设为true
        if (StringUtils.isNotEmpty(collectionResult)) {
            iscollection = true;
        }
        //判断是否关注
        Double followResult = cacheService.zScore(BehaviorConstants.APUSER_FOLLOW_RELATION + userId, dto.getAuthorId().toString());
        if (followResult !=null){
            isfollow = true;
        }

        //组装数据并且返回
        Map<String, Object> map = new HashMap<>(4);
        map.put("islike",islike);
        map.put("isunlike",isunlike);
        map.put("iscollection",iscollection);
        map.put("isfollow",isfollow);

        return ResponseResult.okResult(map);

    }

    //生成静态文件freemaker并上传minio
    @Async
    public void CreateHtmlAndUploadMINIO(Long articleId) {
        //根据article_id把具体内容查出来
        LambdaQueryWrapper<ApArticleContent> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApArticleContent::getArticleId, articleId);
        ApArticleContent articleContent = apArticleContentMapper.selectOne(wrapper);
        //具体内容
        String content = articleContent.getContent();
        //判空
        if (content == null || StringUtils.isEmpty(content)) {
            return;
        }
        //利用freemaker将具体内容生成静态化html
        Map<String, Object> map = new HashMap<>();
        map.put("content", JSONArray.parseArray(content));
        InputStream is = freemarkerGenerator.generate("article.ftl", map);

        //将生成的html上传到minio中,并返回地址
        String url = minIoTemplate.uploadFile("", articleContent.getArticleId() + ".html", is, "html");

        //将ap_article表中的static_url更新为该路径
        ApArticle article = apArticleMapper.selectById(articleContent.getArticleId());
        article.setStaticUrl(url);
        apArticleMapper.updateById(article);

        // 6. 发送消息，创建索引
        createArticleESIndex(article, content, url);
    }

    /**
     * 送消息，创建索引
     *
     * @param apArticle
     * @param content
     * @param path
     */
    private void createArticleESIndex(ApArticle apArticle, String content, String path) {
        SearchArticleVo vo = new SearchArticleVo();
        BeanUtils.copyProperties(apArticle, vo);
        vo.setContent(content);
        vo.setStaticUrl(path);

        kafkaTemplate.send("article.es.sync.topic", JSON.toJSONString(vo));
    }


}
